package com.lagou.edu.service.impl;

import com.lagou.edu.dao.entity.User;
import com.lagou.edu.dao.repository.UserRepository;
import com.lagou.edu.service.RegisterService;
import com.lagou.edu.service.VerificationService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author bobcheng
 * @date 2020/7/13
 */
@Service
public class RegisterServiceImpl implements RegisterService {

    @Reference
    private VerificationService verificationService;
    @Autowired
    private UserRepository userRepository;


    @Override
    @Transactional
    public boolean register(String email, String password, String code) {
        if (isRegistered(email)) {
            return false;
        }
        int validate = verificationService.validate(email, code);
        if (validate != 0) {
            return false;
        }
        User user = User.builder().email(email).password(password).build();
        userRepository.save(user);
        return true;
    }

    public boolean isRegistered(String email) {
        User user = userRepository.findTopByEmail(email);
        return Objects.nonNull(user);
    }
}
